var formidable = require('formidable');
var path = require('path');
var url = require('url');
var fs = require('fs');
var xlsx = require('node-xlsx');
var Student = require('../models/Student')
var Course = require('../models/Course')
var mongoose = require('mongoose')
var format = require('date-format')
var common = require('./common')

function showAdminIndex(req, res) {
    res.render("admin/index", {
        page: 'index'
    });
}

function showLogin (req, res) {
    res.render('admin/student/login')
}

function doLogin (req, res) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, fiels) {
        Student.find({ 'sid': fields.sid }, function (err, result) {
            if (err) {
                res.json({ result: -1 }) //查找时出错，服务器问题
                return
            }
            if (result.length === 0) {
                res.json({ result: -2 }) //查找时出错，没有这个学号
                return
            }
            //判断有没有修改过密码
            var stu = result[0];
            // console.log(result[0])
            //没有修改过密码的情况，直接拿数据库的原始密码和该学生输入的进行对比
            if (!stu.changePassword) {
                if (stu.password === fields.password) {
                    req.session.isLogin = true
                    req.session.sid = stu.sid
                    req.session.sname = stu.sname
                    req.session.grade = stu.grade
                    req.session.changePassword = false
                    req.session.courses = stu.courses
                    res.json({ result: 1 })  //登录成功

                }
                else {
                    res.json({ result: -3 })  //用户输入的密码错误
                }
            }else {

                if (stu.password === common.md5(fields.password)) {
                    req.session.isLogin = true
                    req.session.sid = stu.sid
                    req.session.sname = stu.sname
                    req.session.grade = stu.grade
                    req.session.changePassword = true
                    req.session.courses = stu.courses
                    res.json({ result: 1 })  //登录成功

                }
                else {
                    res.json({ result: -3 })  //用户输入的密码错误
                }
            }

        })
    })
}

function showSignUpIndex (req, res) {
    if (!req.session.isLogin) {
        res.redirect('/login')
        return
    }
    if (!req.session.changePassword) {
        res.render('admin/student/changePassword', {
            sid: req.session.sid,
            sname: req.session.sname,
            grade: req.session.grade,
            changePassword: req.session.changePassword
        })
        return
    }
    res.render('admin/student/index', {
        sid: req.session.sid,
        sname: req.session.sname,
        grade: req.session.grade,
    })
}

function showChangePassword (req, res) {
    if (!req.session.isLogin) {
        res.redirect('/login')
        return
    }
    res.render('admin/student/changePassword', {
        sid: req.session.sid,
        sname: req.session.sname,
        grade: req.session.grade,
        changePassword: req.session.changePassword
    })
}

function exitLogin (req, res) {
    //清空session
    req.session.isLogin = false
    req.session.sid = ''
    req.session.sname = ''
    res.redirect('/login')
}

function doChangePassword (req, res) {
    if (!req.session.isLogin) {
        res.redirect('/login')
        return
    }
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields) {
        Student.find({ 'sid': req.session.sid }, function (err, result) {
            if (err || result.length === 0) {
                res.json({ result: -1 }) //查找出错
                return
            }
            result[0].password = common.md5(fields.password)
            result[0].changePassword = true
            result[0].save(function (err) {
                if (err) {
                    res.json({ result: -2 }) //保存出错
                    return
                }
                res.json({ result: 1 }) //修改成功
            })
        })

    })
}

//检查一个学生是否可以选报某些课程
function weatherCanSignUp (req, res) {
    if (!req.session.isLogin) {
        res.redirect('/login')
        return
    }
    Student.find({ 'sid': req.session.sid }, function (err, students) {
        if (err || students.length === 0) {
            res.json({ result: -1 })
            return
        }
        var stu = students[0];
        var allow = {}  //表示当前可以该名学生可以选的课程情况
        var occpyWeek = []   //表示当前学生已选的选修课占用的星期
        Course.find({}, function (err, courses) {
            if (err || courses.length === 0) {
                res.json({ result: -1 })
                return
            }

            // 遍历该学生已选的课程，得出已被占用的星期
            stu.courses.forEach(function (cou) {   //courses: [2, 5]
                courses.forEach(function (item) {
                    if (item.cid === cou) {  //如果学生的选的课程等于课程表中的课程，就把该课程所占用的时间记录下来，保存到occpyweek
                        occpyWeek.push(item.dayofweek[0])
                    }
                })
            })
            courses.forEach(function (item) {
                //判断报名人数，年级，选课上限，上课时间的逻辑
                if (!item.allow.includes(req.session.grade)) {
                    allow[item.cid] = '年级不符合'
                }else if (occpyWeek.includes(item.dayofweek[0])) {
                    if (stu.courses.includes(item.cid)) {
                        allow[item.cid] = '已选'
                    }else {
                        allow[item.cid] = '该时段已选课'
                    }
                }else if (item.number <= 0) {
                    allow[item.cid] = '人数达到上限'
                }else if (stu.courses.length === 2) {
                    allow[item.cid] = '选课达到上限'
                }else {
                    allow[item.cid] = '可选'
                }
            })

            //最后返回课程
            res.json({ result: allow })
        })
    })
}

function selectCourse (req, res) {
    if (!req.session.isLogin) {
        res.redirect('/login')
        return
    }
    var form = new formidable.IncomingForm()
    form.parse(req, function (err, fields, files) {
        Student.find({ 'sid': req.session.sid }, function (err, student) {
            if (err || student.length === 0) {
                res.send({ result: -1 })
                return
            }
            //先检查有没有这个课程
            Course.find({ 'cid': fields.cid }, function (err, course) {
                if (err || course.length === 0) {
                    res.json({ result: -1 })   //查找失败
                    return
                }
                var cou = course[0];
                //检验该学生是否有选修该门课程
                var stu = student[0]
                //如果有选修过该门课程，那么就退报
                if (stu.courses.includes(fields.cid)) {
                    stu.courses.splice(stu.courses.indexOf(fields.cid), 1)  //学生增加这门课程
                    stu.save(function (err) {
                        if (!err) {
                            cou.number ++;
                            cou.students.splice(cou.students.indexOf(stu.cid), 1)  //课程添加学生
                            console.log('执行了' + cou.students);
                            cou.save(function (err) {
                                if (!err) {
                                    req.session.courses = stu.courses  //更新课程的session
                                    res.send({ result: 0 })   //0表示退课成功
                                }
                            })
                        }
                    })
                }else {
                    stu.courses.push(fields.cid)
                    stu.save(function (err) {
                        if (cou.number <= 0) {
                            res.send({ result: -2 })   //-2表示人数不足
                            return
                        }
                        cou.number --;
                        cou.students.push( stu.sid )
                        cou.save(function (err) {
                            if (!err) {
                                req.session.courses = stu.courses  //更新课程的session
                                res.send({ result: 1 })   //1表示选课成功
                            }
                        })
                    })
                }

            })
        })
    })
}

function showAdminIndexByStudent(req, res) {
    res.render('admin/index_showByStudent', {
        page: 'index'
    })
}


module.exports = {
    showAdminIndex,
    showLogin,
    doLogin,
    showSignUpIndex,
    showChangePassword,
    doChangePassword,
    exitLogin,
    weatherCanSignUp,
    selectCourse,
    showAdminIndexByStudent
}